package cn.cf.kxx;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Arrays;

import cn.cf.kxx.adapter.WeatherAdapter;
import cn.cf.kxx.data.DataSharedPreferences;
import cn.cf.kxx.fram.OnActivityInteractionListener;
import cn.cf.kxx.fram.OnFragmentInteractionListener;
import cn.cf.kxx.model.Farm;
import cn.cf.kxx.tools.OkHttpUtils;
import cn.cf.kxx.tools.Tools;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends Fragment implements View.OnClickListener , OnFragmentInteractionListener {

    byte[] bytes;

    @Override
    public void onRefrashString(String type) {
        refrash();
    }

    @Override
    public void onRefrashValve(int status) {
        if(status == 1){
            valStatus.setText("已打开");
        }else{
            valStatus.setText("已关闭");
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    public void onRefrashValues(Object obj) {


        byte[] content = (byte[]) obj;
        if(!Arrays.equals(bytes,content)){
            bytes = content;


            //更新UI
            flow.setText(String.valueOf(Tools.IEE754Parser(Arrays.copyOfRange(bytes,0,4))));
            pressure.setText(String.valueOf(Tools.TwoByteParserLit(Arrays.copyOfRange(bytes,11,13))));
            fatPres.setText(String.valueOf(Tools.TwoByteParserLit(Arrays.copyOfRange(bytes,13,15))));
            fatFlow.setText(String.valueOf(Tools.TwoByteParserLit(Arrays.copyOfRange(bytes,15,17))));

            //肥池
            byte di = bytes[19];
            if((di >> 5 & 1) == 1){
                level.setText("液位低");
            }else if((di >> 6 & 1) == 1){
                level.setText("液位高");
            }else{
                level.setText("正常");
            }

            //电机
            if((di & 1) == 0){
                pumpSw.setTag(null);
                pumpSwTxt.setText("水泵已关闭");
                pumpSw.setBackground(getResources().getDrawable(R.drawable.btn_bg,null));
                pumpImage.clearAnimation();
            }else{
                pumpSw.setTag("pump");
                pumpSwTxt.setText("水泵已启动");
                pumpSw.setBackground(getResources().getDrawable(R.drawable.btn_bg_green,null));
                startAnimation(pumpImage);
            }
            if((di >> 1 & 1) == 0){
                fertilizerSw.setTag(null);
                fertilizerSwTxt.setText("肥泵已关闭");
                fertilizerSw.setBackground(getResources().getDrawable(R.drawable.btn_bg,null));
                fertilizerImage.clearAnimation();
            }else{
                fertilizerSw.setTag("fertilizer");
                fertilizerSwTxt.setText("肥泵已启动");
                fertilizerSw.setBackground(getResources().getDrawable(R.drawable.btn_bg_green,null));
                startAnimation(fertilizerImage);
            }
            if((di >> 2 & 1) == 0){
                blenderSw.setTag(null);
                blenderSwTxt.setText("搅拌已关闭");
                blenderSw.setBackground(getResources().getDrawable(R.drawable.btn_bg,null));
                blenderImage.clearAnimation();
                blenderTime = 0;
                mHandler.removeCallbacks(mRunnable);
            }else{
                blenderSw.setTag("blender");
                blenderSwTxt.setText("搅拌已启动");
                blenderSw.setBackground(getResources().getDrawable(R.drawable.btn_bg_green,null));
                startAnimation(blenderImage);
                // 在需要启动定时器的地方调用以下代码
                mHandler.postDelayed(mRunnable, 60000);
            }
        }
    }

    byte[] beiFen;

    @Override
    public void onPause() {
        super.onPause();
        if(bytes != null){
            beiFen = Arrays.copyOf(bytes,bytes.length);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(beiFen != null){
            bytes = null;
            onRefrashValues(beiFen);
            beiFen = null;
        }
    }

    private int blenderTime = 0;

    private Handler mHandler = new Handler();
    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            // 定时任务执行的逻辑代码
            // 每分钟执行一次这里的代码
            blenderTime += 1;
            blenderState.setText(blenderTime + "分");
            // 再次调度下一次执行
            mHandler.postDelayed(this, 60000);
        }
    };

    OnActivityInteractionListener onActivityInteractionListener;
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        onActivityInteractionListener = (OnActivityInteractionListener) context;
    }

    View contentView;

    GridView weather;

    public static MainActivity newInstance(Bundle args) {
        MainActivity fragment = new MainActivity();
        fragment.setArguments(args);
        return fragment;
    }

    TextView pumpSwTxt,fertilizerSwTxt,blenderSwTxt,valStatus,flow,pressure,fatFlow,fatPres,level;

    LinearLayout pumpSw,fertilizerSw,blenderSw;

    TextView valOpen,valClose,blenderState,farmName;

    ImageView pumpImage,fertilizerImage,blenderImage;

    DataSharedPreferences sharedPreferences;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedPreferences = DataSharedPreferences.getInstance();
    }

    WeatherAdapter weatherAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if(contentView == null){
            contentView = inflater.inflate(R.layout.activity_main,container,false);
        }else{
            ViewGroup parent = (ViewGroup) contentView.getParent();
            if (parent != null) {
                parent.removeView(contentView);
            }
        }

        contentView.findViewById(R.id.valve).setOnClickListener(this);
        contentView.findViewById(R.id.pump_control).setOnClickListener(this);
        contentView.findViewById(R.id.fertilizer_control).setOnClickListener(this);
        contentView.findViewById(R.id.exeplan).setOnClickListener(this);
        contentView.findViewById(R.id.setting).setOnClickListener(this);
        contentView.findViewById(R.id.police).setOnClickListener(this);

        pumpSw = contentView.findViewById(R.id.pumpSw);pumpSw.setOnClickListener(this);
        fertilizerSw = contentView.findViewById(R.id.fertilizerSw);fertilizerSw.setOnClickListener(this);
        blenderSw = contentView.findViewById(R.id.blenderSw);blenderSw.setOnClickListener(this);
        valOpen = contentView.findViewById(R.id.valOpen);valOpen.setOnClickListener(this);
        valClose = contentView.findViewById(R.id.valClose);valClose.setOnClickListener(this);
        farmName = contentView.findViewById(R.id.fram);



        pumpSwTxt = contentView.findViewById(R.id.pumpSwTxt);
        fertilizerSwTxt = contentView.findViewById(R.id.fertilizerSwTxt);
        blenderSwTxt = contentView.findViewById(R.id.blenderSwTxt);
        valStatus = contentView.findViewById(R.id.valStatus);

        flow = contentView.findViewById(R.id.flow);
        pressure = contentView.findViewById(R.id.pressure);
        fatFlow = contentView.findViewById(R.id.fatFlow);
        fatPres = contentView.findViewById(R.id.fatPres);
        level = contentView.findViewById(R.id.level);
        blenderState = contentView.findViewById(R.id.blenderState);

        pumpImage = contentView.findViewById(R.id.pumpImage);
        fertilizerImage = contentView.findViewById(R.id.fertilizerImage);
        blenderImage = contentView.findViewById(R.id.blenderImage);

        weather = contentView.findViewById(R.id.weather);
        weatherAdapter = new WeatherAdapter(getActivity(),new JSONArray());
        weather.setAdapter(weatherAdapter);

        //根据缓存状态一小时刷新一次当天天气预报存入，并显示
        refrash();
        return contentView;
    }

    private void refrash(){
        String data = sharedPreferences.getFarm(getActivity());
        if(!TextUtils.isEmpty(data)){
            try {
                JSONObject jo = new JSONObject(data);
                farmName.setText(jo.getString("name"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        data = sharedPreferences.getWeather(getActivity());
        if(!TextUtils.isEmpty(data)){
            try {
                JSONArray ja = new JSONArray(data);
                Log.e("dong","天气预报条数"+ja.length());
                weatherAdapter.setmDataList(ja);
                weatherAdapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View v) {
        Object tag = v.getTag();

        if (v.getId() == R.id.valve){
            onActivityInteractionListener.startFragment(5);
        }else if(v.getId() == R.id.pump_control){
            onActivityInteractionListener.startFragment(1);
        }else if(v.getId() == R.id.fertilizer_control){
            onActivityInteractionListener.startFragment(2);
        }else if(v.getId() == R.id.exeplan){
            onActivityInteractionListener.startFragment(3);
        }else if(v.getId() == R.id.setting){
            onActivityInteractionListener.startFragment(7);
        }else if(v.getId() == R.id.police){
            onActivityInteractionListener.startFragment(6);
        }else if(v.getId() == R.id.pumpSw){
            if(tag == null){
                v.setTag("pump");
                pumpSwTxt.setText("水泵启动中...");
                v.setBackground(getResources().getDrawable(R.drawable.btn_bg_green,null));
                onActivityInteractionListener.sendCommand(5,3,1,new byte[]{1});
            }else{
                v.setTag(null);
                pumpSwTxt.setText("水泵关闭中...");
                v.setBackground(getResources().getDrawable(R.drawable.btn_bg,null));
                onActivityInteractionListener.sendCommand(5,3,1,new byte[]{0});
            }
        }else if(v.getId() == R.id.fertilizerSw){
            if(tag == null){
                v.setTag("fertilizer");
                fertilizerSwTxt.setText("肥泵启动中...");
                v.setBackground(getResources().getDrawable(R.drawable.btn_bg_green,null));
                onActivityInteractionListener.sendCommand(5,4,1,new byte[]{1});
            }else{
                v.setTag(null);
                fertilizerSwTxt.setText("肥泵关闭中...");
                v.setBackground(getResources().getDrawable(R.drawable.btn_bg,null));
                onActivityInteractionListener.sendCommand(5,4,1,new byte[]{0});
            }
        }else if(v.getId() == R.id.blenderSw){
            if(tag == null){
                v.setTag("blender");
                blenderSwTxt.setText("搅拌启动中...");
                v.setBackground(getResources().getDrawable(R.drawable.btn_bg_green,null));
                onActivityInteractionListener.sendCommand(5,5,1,new byte[]{1});
            }else{
                v.setTag(null);
                blenderSwTxt.setText("搅拌关闭中...");
                v.setBackground(getResources().getDrawable(R.drawable.btn_bg,null));
                onActivityInteractionListener.sendCommand(5,5,1,new byte[]{0});
            }
        }else if(v.getId() == R.id.valOpen){
            valStatus.setText("已打开");
            onActivityInteractionListener.sendCommand(5,6,1,new byte[]{1});
        }else if(v.getId() == R.id.valClose){
            valStatus.setText("已关闭");
            onActivityInteractionListener.sendCommand(5,6,1,new byte[]{0});
        }
    }

    RotateAnimation rotateAnimation;

    private void startAnimation(ImageView imageView){
        // 创建一个RotateAnimation对象，并设置旋转的角度和持续时间
        if(rotateAnimation == null){
            rotateAnimation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(1000); // 设置动画持续时间为1秒
            rotateAnimation.setInterpolator(new LinearInterpolator()); // 设置线性插值器
            // 设置动画的重复次数，这里设置为无限循环
            rotateAnimation.setRepeatCount(Animation.INFINITE);
        }
        // 开始动画
        imageView.startAnimation(rotateAnimation);
    }

}